//
//  CardView.swift
//  book
//
//  Created by 孙磊 on 2019/3/17.
//  Copyright © 2019 sunlei. All rights reserved.
//

import UIKit

class CardView: UIView {
    private var collectionView:UICollectionView?
    private var layout:CollectionLayout?
    private var page = 0
    private var pageFrame = UIScreen.main.bounds.size.width - 60
    private var sectionCount = 50
    
    var backView:UIView!
    var imgView:UIImageView!
    
    
    private var imgUrl = ["st","sf","four","qop","jt"]
    private var changePageTimer:Timer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
        setupTimer()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupTimer(){
        
        changePageTimer = Timer(timeInterval: 5, target: self, selector: #selector(autoNextPage), userInfo: nil, repeats: true)
        
        RunLoop.main.add(changePageTimer!, forMode: RunLoop.Mode.common)
    }
    
    private func setupUI(){
        
        layout = CollectionLayout()
        layout?.itemSize = CGSize(width: Screen.Width - 80, height: 200)
        
        let blackBack = UIView(frame: CGRect(x: 0, y: 0, width: Screen.Width , height: 66 + 125))
        blackBack.backgroundColor = UIColor.black
//        self.addSubview(blackBack)
        
        let backButton    = UIButton(frame: CGRect(x: 15, y: 15, width: 21, height: 35))
        backButton.setImage(UIImage(named: "left_arrow_"),     for: .normal)
        backButton.addTarget(self, action: #selector(popSelf), for: .touchUpInside)
        blackBack.addSubview(backButton)  
        
        
        let rect = CGRect(x: 0, y: 66, width:Screen.Width, height: 250)
        collectionView = UICollectionView(frame: rect, collectionViewLayout: layout!)
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.delegate = self
        collectionView?.dataSource = self
        collectionView?.bounces = false
        collectionView?.register(CardCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        collectionView?.backgroundColor = UIColor.clear
        
        collectionView?.decelerationRate = UIScrollView.DecelerationRate.fast
        self.addSubview(collectionView!)
        
        //        view.bringSubview(toFront: titleView)
        
    }
    
    @objc private func autoNextPage(){
        
        guard page < sectionCount * imgUrl.count - 1 else {
            
            changePageTimer?.invalidate()
            return
            
        }
        
        page += 1
        
        
        let nextPoint = CGPoint(x: CGFloat (page) * pageFrame, y: 0)
        
        
        collectionView?.setContentOffset(nextPoint, animated: true)
        
    }
    
//    override func viewDidDisappear(_ animated: Bool) {
//        changePageTimer?.invalidate()
//    }
    
    deinit {
        print("CardViewController is release")
    }
    
//    override func didReceiveMemoryWarning() {
//        super.didReceiveMemoryWarning()
//        // Dispose of any resources that can be recreated.
//    }
    
    @objc private func popSelf(){
        
//        self.navigationController?.popViewController(animated: true)
        
    }
    
}


extension CardView:UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionCount
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imgUrl.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CardCell
        cell.imgView.image = UIImage(named: imgUrl[indexPath.item])
        return cell
    }
    
}

extension CardView:UICollectionViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        page = Int(scrollView.contentOffset.x / pageFrame)
        
        setupTimer()
        
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        changePageTimer?.invalidate()
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
}

extension CardView:UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        switch section {
        case 0:
            return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 20)
        case section - 1:
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 40)
        default:
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20)
        }
        
    }
    
}



class CollectionLayout:UICollectionViewFlowLayout {
    
    private let scaleFactor:CGFloat = 0.001
    
    override func prepare() {
        
        super.prepare()
        scrollDirection = .horizontal
        minimumLineSpacing = 20.0
        
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        
        return true
        
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        let array:[UICollectionViewLayoutAttributes] =  NSArray.init(array: super.layoutAttributesForElements(in: rect)!, copyItems: true) as! [UICollectionViewLayoutAttributes]
        let centerX = (collectionView?.contentOffset.x)! + (collectionView?.bounds.size.width)! / 2
        
        for attr in array {
            
            let cell_centerX = attr.center.x
            let distance = abs(cell_centerX - centerX)
            let scale:CGFloat = 1 / ( 1 + distance * scaleFactor)
            attr.transform3D = CATransform3DMakeScale(1.0, scale, 1.0)
        }
        
        return array
        
        
    }
    
    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        let visibleX = proposedContentOffset.x
        let visibleY = proposedContentOffset.y
        let visibleW = collectionView?.bounds.size.width
        let visibleH = collectionView?.bounds.size.height
        //获取可视区域
        let targetRect = CGRect(x: visibleX, y: visibleY, width: visibleW!, height: visibleH!)
        
        //中心点的值
        let centerX = proposedContentOffset.x + (collectionView?.bounds.size.width)!/2
        
        //获取可视区域内的attributes对象
        let attrArr = super.layoutAttributesForElements(in: targetRect)!
        //如果第0个属性距离最小
        var min_attr = attrArr[0]
        for attributes in attrArr {
            if (abs(attributes.center.x-centerX) < abs(min_attr.center.x-centerX)) {
                min_attr = attributes
            }
        }
        //计算出距离中心点 最小的那个cell 和整体中心点的偏移
        let ofsetX = min_attr.center.x - centerX
        return CGPoint(x: proposedContentOffset.x+ofsetX, y: proposedContentOffset.y)
    }
    
}

class CardCell: UICollectionViewCell {
    
    var imgView:UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let backView = UIView(frame:contentView.bounds)
        addSubview(backView)
        
        backView.layer.shadowOpacity = 0.08
        backView.layer.shadowColor = UIColor.black.cgColor
        backView.layer.shadowOffset = CGSize(width: 10, height: 10)
        backView.layer.shadowRadius = 3
        
        imgView = UIImageView(frame:contentView.bounds)
        imgView.layer.cornerRadius = 10
        imgView.layer.masksToBounds = true
        backView.addSubview(imgView)
        
        contentView.addSubview(backView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}
